package org.ghost.spring.cloud.consumer.demo.common.converter;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.ghost.spring.cloud.consumer.demo.util.DateUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 字符型String转字符型数组
 */
@Component
public class String2StringArraysConverter implements Converter<String, String[]> {
    @Override
    public String[] convert(String source) {
        if (StringUtils.isNotBlank(source)) {
            String[] data = source.split("\\,");
            if (ArrayUtils.isNotEmpty(data)) {
                List<String> list = new ArrayList<>();
                for (String item : data) {
                    try {
                        //先判断是否时间戳
                        list.add(DateUtil.dateToStrYMD_HMS(new Date(Long.valueOf(item))));
                    } catch (Exception e) {
                        list.add(DateUtil.dateToStrYMD_HMS(DateUtil.strToDateYMD_HMS(item)));
                    }
                }
                String[] result = new String[list.size()];
                list.toArray(result);
                return result;
            }
        }

        return null;
    }
}